#include "carel-device-ui/main_ui.h"
#include "plugin/scenes/scenes.h"

#if !defined ZCL_TUYA_EXT_SCENE_CMD_COMMAND_ID
#define ZCL_TUYA_EXT_SCENE_CMD_COMMAND_ID 0xFB
#endif

#define emberAfFillCommandOnOffClustertuya_ext_scene_cmd() \
  emberAfFillExternalBuffer((ZCL_CLUSTER_SPECIFIC_COMMAND \
		  	  	  	  	  	 | ZCL_DISABLE_DEFAULT_RESPONSE_MASK \
                             | ZCL_FRAME_CONTROL_CLIENT_TO_SERVER), \
                            ZCL_ON_OFF_CLUSTER_ID, \
                            ZCL_TUYA_EXT_SCENE_CMD_COMMAND_ID, \
                            "");

int z3Ext_SceneRecall(uint8_t ep){

	EmberAfSceneTableEntry entry;
	bool hasFound = false;

	for (uint8_t index = 0; index < EMBER_AF_PLUGIN_SCENES_TABLE_SIZE; index++) {
		memset(&entry, 0, sizeof(EmberAfSceneTableEntry));
		emberAfPluginScenesServerRetrieveSceneEntry(entry, index);
		if (entry.endpoint == ep) {
			hasFound = true;
			break;
		}
	}

	if(!hasFound){
		UTILS_PRINT(UPM_EXT_SCENE, "scene id not found on ep: %d\n", ep);
		return -1;
	}

	UTILS_PRINT(UPM_EXT_SCENE,
			"Invoke Recall!! ep: %d, group: %04X, scene: %02X\n",
			ep,
			entry.groupId,
			entry.sceneId);

	emberAfSetCommandEndpoints(ep, 0xFF);
	emberAfFillCommandScenesClusterRecallScene(entry.groupId, entry.sceneId, 0);
//	emberAfSendCommandUnicastToBindings();
	emberAfSendCommandMulticast(entry.groupId);

	emberAfSetCommandEndpoints(ep, 1);
	emberAfFillCommandOnOffClustertuya_ext_scene_cmd();
//	emberAfSendCommandUnicastToBindings();
	emberAfSendCommandUnicast(EMBER_OUTGOING_DIRECT, 0x0000);

	return 0;
}

void z3Ext_SceneTableClearByEndpoint(uint8_t endpoint){

	EmberAfSceneTableEntry entry;

	for (uint8_t index = 0; index < EMBER_AF_PLUGIN_SCENES_TABLE_SIZE; index++) {
		memset(&entry, 0, sizeof(EmberAfSceneTableEntry));
		emberAfPluginScenesServerRetrieveSceneEntry(entry, index);
		if (entry.endpoint == endpoint) {
			entry.endpoint = EMBER_AF_SCENE_TABLE_UNUSED_ENDPOINT_ID;
			emberAfPluginScenesServerSaveSceneEntry(entry, index);
			emberAfPluginScenesServerDecrNumSceneEntriesInUse();
			emberAfScenesSetSceneCountAttribute(endpoint,
							emberAfPluginScenesServerNumSceneEntriesInUse());
		}
	}
}
